<template>
  <view class="car-verify-container">
    <u-form :model="carForm" ref="carFormRef" :rules="rules" label-position="top">
      <u-form-item label="员工姓名" prop="userName">
        <u-input v-model="carForm.userName" placeholder="请输入员工姓名" disabled />
      </u-form-item>
      
      <u-form-item label="部门" prop="department">
        <u-input v-model="carForm.department" placeholder="请输入部门" disabled />
      </u-form-item>
      
      <u-form-item label="车牌号" prop="carNumber">
        <u-input v-model="carForm.carNumber" placeholder="请输入车牌号" />
      </u-form-item>
      
      <u-form-item label="用车日期" prop="useDate">
        <u-datetime-picker
          v-model="carForm.useDate"
          mode="date"
          :show-toolbar="true"
          @confirm="dateConfirm">
          <u-input
            v-model="carForm.useDateDisplay"
            placeholder="请选择用车日期"
            disabled
            suffixIcon="calendar"
          />
        </u-datetime-picker>
      </u-form-item>
      
      <u-form-item label="起始里程" prop="startMileage">
        <u-input
          v-model="carForm.startMileage"
          placeholder="请输入起始里程"
          type="number"
          @input="calculateTravelMileage"
        />
      </u-form-item>
      
      <u-form-item label="终止里程" prop="endMileage">
        <u-input
          v-model="carForm.endMileage"
          placeholder="请输入终止里程"
          type="number"
          @input="calculateTravelMileage"
        />
      </u-form-item>
      
      <u-form-item label="行驶里程" prop="travelMileage">
        <u-input v-model="travelMileage" disabled />
      </u-form-item>
      
      <u-form-item label="报销金额" prop="amount">
        <u-input
          v-model="carForm.amount"
          placeholder="请输入报销金额"
          type="number"
          suffix-icon="rmb-circle"
        />
      </u-form-item>
      
      <u-form-item label="用车事由" prop="reason">
        <u-textarea v-model="carForm.reason" placeholder="请输入用车事由" />
      </u-form-item>
      
      <u-form-item label="行车路线" prop="route">
        <u-textarea v-model="carForm.route" placeholder="请输入行车路线" />
      </u-form-item>
      
      <view class="form-actions">
        <u-button type="primary" @click="submitForm" :loading="loading">提交验证</u-button>
        <u-button @click="resetForm" :disabled="loading">重置</u-button>
      </view>
    </u-form>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {
      loading: false,
      carForm: {
        userName: '',
        department: '',
        carNumber: '',
        useDate: '',
        useDateDisplay: '',
        startMileage: '',
        endMileage: '',
        amount: '',
        reason: '',
        route: ''
      },
      rules: {
        carNumber: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5][A-Z][A-Z0-9]{5}$/, message: '请输入正确的车牌号格式', trigger: 'blur' }
        ],
        useDate: [
          { required: true, message: '请选择用车日期', trigger: 'change' }
        ],
        startMileage: [
          { required: true, message: '请输入起始里程', trigger: 'blur' }
        ],
        endMileage: [
          { required: true, message: '请输入终止里程', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value && this.carForm.startMileage && Number(value) <= Number(this.carForm.startMileage)) {
                callback(new Error('终止里程必须大于起始里程'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        amount: [
          { required: true, message: '请输入报销金额', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额格式', trigger: 'blur' }
        ],
        reason: [
          { required: true, message: '请输入用车事由', trigger: 'blur' }
        ],
        route: [
          { required: true, message: '请输入行车路线', trigger: 'blur' }
        ]
      },
      travelMileage: ''
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  onLoad() {
    // 设置用户信息
    this.carForm.userName = this.userInfo.name || ''
    this.carForm.department = '财务部' // 模拟数据，实际应从用户信息获取
  },
  methods: {
    // 日期确认
    dateConfirm(e) {
      this.carForm.useDateDisplay = this.$utils.formatDate(e.value, 'YYYY-MM-DD')
    },
    
    // 计算行驶里程
    calculateTravelMileage() {
      if (this.carForm.startMileage && this.carForm.endMileage) {
        const start = Number(this.carForm.startMileage)
        const end = Number(this.carForm.endMileage)
        
        if (!isNaN(start) && !isNaN(end) && end > start) {
          this.travelMileage = (end - start).toFixed(2)
          
          // 自动计算金额（假设单价为0.6元/公里）
          const suggestedAmount = (end - start) * 0.6
          if (!this.carForm.amount) {
            this.carForm.amount = suggestedAmount.toFixed(2)
          }
        } else {
          this.travelMileage = ''
        }
      } else {
        this.travelMileage = ''
      }
    },
    
    // 提交表单
    submitForm() {
      this.$refs.carFormRef.validate(async valid => {
        if (!valid) return
        
        this.loading = true
        
        try {
          // 模拟API请求
          setTimeout(() => {
            uni.showToast({
              title: '提交成功',
              icon: 'success'
            })
            
            // 跳转到结果页
            uni.navigateTo({
              url: '/pages/car/result'
            })
            
            this.loading = false
          }, 1500)
          
          // 实际项目中应该是这样的API调用
          // const result = await this.$http.post('/car/verify', this.carForm)
          // if (result.code === 0) {
          //   uni.showToast({
          //     title: '提交成功',
          //     icon: 'success'
          //   })
          //   
          //   // 跳转到结果页，并传递结果ID
          //   uni.navigateTo({
          //     url: `/pages/car/result?id=${result.data.id}`
          //   })
          // } else {
          //   uni.showToast({
          //     title: result.message || '提交失败',
          //     icon: 'none'
          //   })
          // }
        } catch (error) {
          uni.showToast({
            title: '提交失败，请重试',
            icon: 'none'
          })
        } finally {
          this.loading = false
        }
      })
    },
    
    // 重置表单
    resetForm() {
      this.$refs.carFormRef.resetFields()
      this.carForm.useDateDisplay = ''
      this.travelMileage = ''
      
      // 重新设置用户信息
      this.carForm.userName = this.userInfo.name || ''
      this.carForm.department = '财务部'
    }
  }
}
</script>

<style lang="scss" scoped>
.car-verify-container {
  padding: 30rpx;
  background-color: #ffffff;
  min-height: 100vh;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 50rpx;
  margin-bottom: 30rpx;
  
  .u-button {
    width: 45%;
  }
}
</style> 